package handler

import (
	"github.com/gin-gonic/gin"
	"pic-text-mgr/model"
	"pic-text-mgr/pkg"
	"strconv"
)

func Login(c *gin.Context) {
	tel := c.PostForm("tel")
	password := c.PostForm("password")
	data := model.User{
		Tel:      tel,
		Password: pkg.Str(password),
	}
	err := model.DB.Where("password = ?", pkg.Str(password)).Error
	if err != nil {
		c.JSON(200, gin.H{
			"code": 400,
			"msg":  "密码不正确",
		})
		return
	}

	err = model.DB.Create(&data).Error
	if err != nil {
		c.JSON(200, gin.H{
			"code": 400,
			"msg":  "登录失败",
		})
		return
	}
	uid := c.Query("uid")
	token := pkg.TokenHandler(uid)
	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "登录成功",
		"data": token,
	})
	return
}

func List(c *gin.Context) {
	page, _ := strconv.Atoi(c.DefaultQuery("page", "1"))
	size, _ := strconv.Atoi(c.DefaultQuery("size", "5"))
	offset := (page - 1) * size
	var picture []model.Picture
	model.DB.Offset(offset).Limit(size).Find(&picture)
	var count int64
	model.DB.Model(&model.Picture{}).Count(&count)
	c.JSON(200, gin.H{
		"code":  200,
		"msg":   "查询成功",
		"data":  picture,
		"count": count,
	})
	return

}
